package com.dtflys.easyel.utils;

import com.dtflys.easyel.ast.ASTType;
import com.dtflys.easyel.exception.EasyElAccessException;
import com.dtflys.easyel.runtime.EasyElObject;
import com.dtflys.easyel.runtime.MetaClass;
import com.dtflys.easyel.runtime.MetaClassFactory;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class AccessUtils {


    public static boolean isGetterName(String name) {
        return name.length() > 3 && name.startsWith("get");
    }


    public static boolean isSetterName(String name) {
        return name.length() > 3 && name.startsWith("set");
    }


    public static String getPropertyName(String name) {
        if (name.length() < 3) return null;
        char firstCharacter = name.charAt(3);
        String body = "";
        if (name.length() > 4) {
            body = name.substring(4);
        }
        return Character.toLowerCase(firstCharacter) + body;
    }


    public static Object accessObject(Object obj, String accessName) throws IllegalAccessException, InvocationTargetException, EasyElAccessException {
        if (obj instanceof EasyElObject) {
            return ((EasyElObject) obj).access(accessName);
        }

        MetaClass metaClass = MetaClassFactory.getMetaClass(obj.getClass());
        return metaClass.access(obj, accessName);
    }

    public static void injectObject(Object obj, String accessName, Object value) throws IllegalAccessException, InvocationTargetException, EasyElAccessException {
        if (obj instanceof EasyElObject) {
            ((EasyElObject) obj).inject(accessName, value);
            return;
        }
        MetaClass metaClass = MetaClassFactory.getMetaClass(obj.getClass());
        metaClass.inject(obj, accessName, value);
    }


    public static Object accessStaticField(ASTType type, String accessName) throws EasyElAccessException, IllegalAccessException {
        return accessStaticField(type.getClazz(), accessName);
    }

    public static Object accessStaticField(Class clazz, String accessName) throws EasyElAccessException, IllegalAccessException {
        MetaClass metaClass = MetaClassFactory.getMetaClass(clazz);
        Field field = metaClass.getStaticField(accessName);
        if (field != null) {
            return field.get(clazz);
        }
        if ("class".equals(accessName)) {
            return metaClass.getClazz();
        }
        throw new EasyElAccessException(clazz, accessName);
    }
}
